<template>
  <div>
    <a-table
      ref="table"
      class="table"
      :bordered="true"
      :columns="columns"
      :data-source="dataSource"
      :customHeaderRow="customHeaderRow"
      :pagination="false"
      :scroll="{ x: 'max-content' }"
    >
      <template
        slot="cell"
        slot-scope="text, record, index, column"
      >
        <div
          style="height: 40px"
          :style="isCellhighlighted(index, column)"
          @click="clickCell(record, index, column)"
        >
          <EditCell
            :table="tableInstance"
            :text="getCellValue(index, column)"
            :showText="text"
            :controlInfo="getControlInfo(column)"
            :factor="getFactor(index, column)"
            @change="changeCell($event, record, index, column)"
          ></EditCell>
        </div>
      </template>
    </a-table>
  </div>
</template>
<script>
import EditCell from './EditCell'
import FCRuleTableInstance from './instance/FCRuleTableInstance'

export default {
  name: 'FCRuleTable',
  components: { EditCell },
  createTable() {
    return FCRuleTableInstance.createTable()
  },
  props: {
    //table实例
    table: Object,
    //规则表类型
    // type: { type: String, default: RuleTableType.simple },
    //列条件因子
    colConditions: Array,
    //行条件因子
    rowConditions: Array,
    //是否⾃动⽣成 table body
    // autoBuild: Boolean,
    //结果因子，快捷方式，会被映射成 colResults/cellResults/rowResults
    results: Array,
    // 列结果因子
    colResults: Array,
    // 单元格结果因子
    cellResults: Array,
    // 行结果因子，当前版本暂不实现
    // rowResults: Array,
    //初始规则数组
    initDatas: Array,
    // 合并表头
    mergedColumns: Array,
    //因子类型
    factorControlList: Array,
    //合并模式
    mergeMode: {
      type: String,
      default: 'drag',
      // default: 'dropdown',
    },
  },
  //
  data() {
    const tableInstance = this.table ?? FCRuleTableInstance.createTable()
    const { colConditions, rowConditions, results, colResults, cellResults, initDatas: rules } = this.$props
    tableInstance.initWithDatas({ colConditions, rowConditions, results, colResults, cellResults, rules })

    const watchProps = ['type', 'colConditions', 'rowConditions', 'autoBuild', 'results']
    const updateColumnMap = ['colConditions', 'rowConditions', 'results']
    // watchProps.forEach((prop) => {
    //   this.$watch(
    //     prop,
    //     (newVal) => {
    //       console.log('watch', prop, newVal)
    //       // if (updateColumnMap.includes(prop)) {
    //       //   tableInstance.updateDatas({ [prop]: newVal })
    //       //   tableInstance.postNotification('column', true)
    //       // }
    //     },
    //     { deep: true }
    //   )
    // })

    return {
      // table 实例，FCRuleTableInstance 对象
      tableInstance,

      //表结构
      columns: tableInstance.buildTableColumns(),
      //表数据
      dataSource: tableInstance.buildTableDataSource(),
      //
      changeNotifier: tableInstance.changeNotifier,

      TESTindex: -1,

      // table 变化存根
      // tableChangeStub: tableInstance.changeStub,
      //简单规则集
      // datas: [],
      //条件因⼦集
      // factors: {},
      //已定义的规则集合
      // rules: [],
      //鼠标状态
      // mouseStatus: '',
      //选中表格头部的dataIndexs
      // selectHeadDataIndexs: [],
      //鼠标点击开始的ColumnsRowIndex
      startColumnsRowIndex: null,
      //鼠标点击开始的Columns
      startColumns: [],
      //鼠标点击开始的th的node标签集合
      startNodeList: [],
      //是否选中了表头
      selectedHead: false,
      //是否显示合并按钮
      showMergeButton: false,
      //是否显示取消按钮
      showSplitButton: false,
      //选中边框
      selectBorder: {
        top: 0,
        left: 0,
        width: 0,
        height: 0,
      },
      //合并表头modal是否显示
      visibleModal: false,
      timeout: '',
      //合并表头
      mergeTitle: '',
      //tableDom
      tableDom: null,
      //table滚动距离
      tableScrollLeft: 0,
      //点击合并弹窗
      visibleMerge: false,
      //点击的所有兄弟column
      nearColumns: [],
      // disabled select at init
      disabledSelect: [],
      mergeData: [],
      mergeColumns: [
        {
          title: '标题',
          dataIndex: 'title',
        },
        {
          title: '合并信息',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          customCell: (record, index) => {
            const obj = { attrs: {}, style: {} }
            console.log('record', record)
            this.mergeData.forEach((item) => {
              if (record.dataIndex === item.dataIndex) {
                if (item.firstIndex === index) {
                  obj.attrs.rowSpan = item.lastIndex - item.firstIndex + 1
                } else if (item.firstIndex < index && item.lastIndex >= index) {
                  obj.style.display = 'none'
                }
              }
            })
            return obj
          },
        },
      ],
      mergeDataSource: [],
      selectedRowKeys: [],
      selectedRows: [],
      selfSelectedRowKeys: [],
    }
  },

  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onSelect: this.onSelectChange,
        columnTitle: ' ',
        getCheckboxProps: this.getCheckboxProps,
      }
    },
    //
    topStyle() {
      return {
        position: 'absolute',
        background: '#2c78eb',
        top: this.selectBorder.top - 1 + 'px',
        left: this.selectBorderLeft + 'px',
        width: this.selectBorder.width + 'px',
        height: '2px',
      }
    },
    bottomStyle() {
      return {
        position: 'absolute',
        background: '#2c78eb',
        top: this.selectBorder.top + this.selectBorder.height - 1 + 'px',
        left: this.selectBorderLeft + 'px',
        width: this.selectBorder.width + 'px',
        height: '2px',
      }
    },
    leftStyle() {
      return {
        position: 'absolute',
        background: '#2c78eb',
        top: this.selectBorder.top + 'px',
        left: this.selectBorderLeft - 1 + 'px',
        width: '2px',
        height: this.selectBorder.height + 'px',
      }
    },
    rightStyle() {
      return {
        position: 'absolute',
        background: '#2c78eb',
        top: this.selectBorder.top + 'px',
        left: this.selectBorderLeft + this.selectBorder.width - 1 + 'px',
        width: '2px',
        height: this.selectBorder.height + 'px',
      }
    },
    contextMenuStyle() {
      return {
        position: 'absolute',
        left: this.formatLeft + 'px',
        top: this.selectBorder.top + this.selectBorder.height + 'px',
        height: '50px',
        background: '#fff',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000,
        borderRadius: '5px',
        cursor: 'pointer',
        boxShadow: '0 2px 8px rgba(0,0,0,.15)',
      }
    },
    selectBorderLeft() {
      return this.selectBorder.left - this.tableScrollLeft
    },
    formatLeft() {
      // if (this.selectBorderLeft + this.selectBorder.width + 310 > window.innerWidth) {
      //   return window.innerWidth - 310
      // } else {
      return this.selectBorderLeft + this.selectBorder.width
      // }
    },
  },
  watch: {
    colConditions(newVal) {
      console.log('newVal', newVal)
      this.updateTable()
    },

    'tableInstance.changeStub': {
      handler(newValue, oldValue) {
        // // 判断newVlaue是否为空
        // const keys = Object.keys(newValue)
        // if (keys.length === 0) return
        // keys.forEach((item) => {
        //   // console.log(item, 'item')
        //   if (item === 'column') {
        //     this.columns = this.tableInstance.buildTableColumns()
        //   } else if (item === 'data') {
        //     // this.dataSource = this.tableInstance.buildTableDataSource()
        //   } else if (item === 'updatedom') {
        //     // console.log('updatedom', newValue[item])
        //     // this.columns = newValue[item]
        //   }
        // })
        if (newValue === 'column') {
          this.columns = this.tableInstance.buildTableColumns()
          console.log(this.columns, 'this.columns')
        }
        this.tableInstance.clearNotification()
      },
    },
    // initDatas() {
    //   this.initData()
    // },
    // colFactors: {
    //   handler() {
    //     this.generateTable()
    //   },
    //   deep: true,
    // },
    // rowFactors: {
    //   handler() {
    //     this.generateTable()
    //   },
    //   deep: true,
    // },
    // factors: {
    //   handler(newValue) {
    //     console.log(newValue, 'factors')
    //   },
    //   deep: true,
    // },
    // rules: {
    //   handler(newValue) {
    //     console.log(newValue, 'rules')
    //   },
    //   deep: true,
    // },
    // datas: {
    //   handler(newValue) {
    //     this.generateTableData(newValue)
    //   },
    // },
  },

  created() {
    // this.tableInstance.setRuleHighLightCell()
    window.addEventListener('click', (event) => {
      console.log('>>>> now click...')
      const target = this.findDom(event.target, 'THEAD')
      // 你可以在这里处理点击事件
      if (target?.tagName !== 'THEAD' && !this.visibleModal) {
        this.clearSelectTable()
      }
    })
    this.$nextTick(() => {
      this.tableDom = this.$refs.table.$el.querySelector('.ant-table-body')
      if (this.dataSource.length === 0) return
      this.tableDom.addEventListener('scroll', () => {
        console.log('>>>> now scroll...')
        this.tableScrollLeft = this.tableDom.scrollLeft
      })
      //禁用右键
      this.$refs.table.$el.addEventListener('contextmenu', (e) => {
        e.preventDefault()
      })
    })
    // this.tableInstance.setRuleHighLightCell()
    // console.log('>>>> now created...')
    // this.initRuleTable()
    // this.generateTable()
    // const tableInstance = this.table ?? FCRuleTableInstance.createTable()
    // const { type, autoBuild, colFactors, rowFactors, results, initDatas: rules } = this.$props
    // const colResults = type === RuleTableType.simple ? results : []
    // const rowResults = []
    // const cellResults = type === RuleTableType.complex ? results : []
    // tableInstance.initWithDatas({ type, autoBuild, colFactors, rowFactors, colResults, rowResults, cellResults, rules })
    // this.tableInstance = tableInstance
    // console.log('>>>>this.table instance is:', this.tableInstance)
  },

  destroyed() {
    window.removeEventListener('click', () => {})
  },

  mounted() {},

  methods: {
    updateTable() {
      console.log('now update table.....', this.colConditions)

      this.tableInstance.updateFactors({
        colConditions: this.colConditions,
        rowConditions: this.rowConditions,
        cellResults: this.cellResults,
        colResults: this.colResults,
        results: this.results,
      })

      this.columns = this.tableInstance.buildTableColumns()
      this.dataSource = this.tableInstance.buildTableDataSource()

      console.log('this.columns:', this.columns)
    },
    showSplitButtons(index) {
      return this.mergeData.some((item) => item.firstIndex === index)
    },

    // isshowMerge(column) {
    //   return ![...this.colConditions, ...this.results, ...this.colResults].some((item) => item.code === column.dataIndex)
    // },

    callback() {},
    //
    // buildTableColumns() {
    // console.log('>> now build table columns..')
    // console.log('>>> this.tableInstance is:', this.tableInstance)
    // return []
    // return this.tableInstance.buildTableColumns()
    // },

    //获取控件类型信息
    getControlInfo(column) {
      // const factor = this.tableInstance.getCellFactorWithDataIndex(column.dataIndex)
      // if (factor.isLink) {
      //   return { type: 'link', openType: factor.linkProps.openType, label: factor.linkProps.label }
      // } else if (factor.isEnum) {
      //   return { type: 'select', options: factor.options }
      // } else {
      //   return { type: 'input' }
      // }

      return { type: 'input' }
    },

    //获取cell值
    getCellValue(index, column) {
      const record = this.tableInstance.getRecordAt(index)
      return record.getCellValue(column.dataIndex)
    },
    //获取factor值
    getFactor(index, column) {
      const record = this.tableInstance.getRecordAt(index)
      return record.getCellFactorWithDataIndex(column.dataIndex)
    },

    //改变单元格值
    changeCell(newValue, dataRecord, index, column) {
      const record = this.tableInstance.getRecordAt(index)
      record.setCellValue({ value: newValue, dataIndex: column.dataIndex })
      const value = record.getCellText(column.dataIndex)
      dataRecord[column.dataIndex] = value
      // console.log(this.dataSource, 'dataSource')
    },

    //是否高亮
    isCellhighlighted(index, column) {
      return false
      // const record = this.tableInstance.getRecordAt(index)
      // return record.getCellStyle(column.dataIndex)
    },

    // 处理选中
    handleSelectChange(dataIndex) {
      return this.mergeData.flatMap((item) => {
        let result = []
        this.mergeDataSource.forEach((item2, index) => {
          if (index >= item.firstIndex && index <= item.lastIndex && item.dataIndices.includes(dataIndex)) {
            result.push(item2.key)
          }
        })
        return result
      })
    },

    //合并表头
    mergeHead(dataIndex) {
      console.log('mergeHead', this.mergeData, dataIndex)
      // this.visibleModal = true
      if (this.mergeData.some((item) => item.dataIndices.includes(dataIndex))) {
        const selectkeys = this.handleSelectChange(dataIndex)
        this.disabledSelect = this.selectedRowKeys = Array.from(new Set([...this.selectedRowKeys, ...selectkeys]))
        console.log(this.selectedRowKeys, 'selectedRowKeys', this.selectedRowKeys, selectkeys)
        this.selfSelectedRowKeys = []
      }
      this.visibleMerge = true
    },
    //合并确定
    handleConfirm() {
      const { mergeTitle, selectHeadDataIndexs } = this
      console.log(selectHeadDataIndexs, mergeTitle, 'selectHeadDataIndexs')
      //todo合并
      this.tableInstance.mergeColumns({ title: mergeTitle, dataIndices: selectHeadDataIndexs })
      this.visibleModal = false
      this.handleMergeClose()
      this.clearSelectTable()
    },
    //拆分表头
    splitHead(index, dataIndex) {
      console.log('splitHead', index)
      const filterMergeData = this.mergeData.find((item) => item.firstIndex === index)
      const dataIndices = []
      this.mergeDataSource.forEach((item, index) => {
        if (index >= filterMergeData.firstIndex && index <= filterMergeData.lastIndex) {
          dataIndices.push(item.dataIndex)
        }
      })
      this.mergeData = this.mergeData.filter((item) => item.firstIndex !== index)
      const selectkeys = this.handleSelectChange(dataIndex)
      const oldselectkeys = this.selectedRows.map((item) => item.key)
      this.selectedRowKeys = Array.from(new Set([...oldselectkeys, ...selectkeys]))
      this.disabledSelect = selectkeys
      this.selfSelectedRowKeys = []
      this.mergeDataSource = this.mergeDataSource.slice()
      const { selectHeadDataIndexs } = this
      //todo拆分
      console.log(dataIndices, 'dataIndices', filterMergeData)
      this.tableInstance.splitColumn(dataIndices)
      this.clearSelectTable()
    },

    //自定义表头
    customHeaderRow(columns, index) {
      return {
        class: 'myClass',
        on: {
          // mousedown: (e) => {
          //   const target = this.findDom(e.target, 'TH')
          //   const column = columns.find((column) => column.dataIndex === target.getAttribute('key'))
          //   if (this.mergeMode === 'drag') {
          //     this.mouseStatus = 'mousedown'
          //     this.clearSelectTable()
          //     this.startColumnsRowIndex = index
          //     this.startColumns = columns
          //     //寻找TH标签元素
          //     if (target?.tagName === 'TH') {
          //       this.startNodeList = target.parentNode.querySelectorAll('th') || []
          //       //有dataIndex可以合并
          //       if (column?.dataIndex && !column.isColColumn) {
          //         this.selectBorder.top = target.offsetTop
          //         this.selectBorder.left = target.offsetLeft
          //         this.selectBorder.width = target.offsetWidth
          //         this.selectBorder.height = target.offsetHeight
          //         target.style.cursor = 'crosshair'
          //         this.selectHeadDataIndexs.push(column.dataIndex)
          //         this.mergeTitle = column.title[0]?.elm?.textContent
          //         this.findNearColumns(column.dataIndex, columns)
          //       }
          //     }
          //   } else if (this.mergeMode === 'dropdown') {
          //     if (column?.dataIndex && !column.isColColumn) {
          //       this.visibleMerge = true
          //       this.findNearColumns(column.dataIndex, columns)
          //     }
          //   }
          // },
          // mousemove: (e) => {
          //   if (e.target.tagName === 'TH' && this.mouseStatus === 'mousedown' && this.mergeMode === 'drag') {
          //     this.selectBorder.width = 0
          //     //根据mousedown鼠标位置计算选中区域
          //     const start = this.selectHeadDataIndexs[0]
          //     const end = e.target.getAttribute('key') ?? start
          //     if (!(start && end)) {
          //       this.selectBorder.height = 0
          //       return
          //     }
          //     const selectDataIndex = this.findAllSelectDataIndex(columns, start, end, index)
          //     this.startNodeList.forEach((item) => {
          //       if (selectDataIndex.includes(item.getAttribute('key'))) {
          //         this.selectBorder.width = this.selectBorder.width += item.offsetWidth
          //       }
          //     })
          //     e.target.style.cursor = 'crosshair'
          //     this.selectHeadDataIndexs = selectDataIndex
          //   } else if (this.mergeMode === 'dropdown') {
          //     //todo点选实现效果
          //     e.target.style.cursor = 'pointer'
          //   }
          // },
          // mouseup: (e) => {
          //   if (this.mergeMode === 'drag') {
          //     this.mouseStatus = 'mouseup'
          //     e.currentTarget.parentNode.querySelectorAll('th').forEach((item) => {
          //       item.style.cursor = 'default'
          //     })
          //     const length = this.selectHeadDataIndexs.length
          //     if (length) {
          //       this.selectedHead = true
          //       if (length >= 2) {
          //         this.showMergeButton = true
          //         this.showSplitButton = false
          //       }
          //       //todo判断是否是拆分的
          //       // const isSplit = this.tableInstance.getMergedColumns(this.selectHeadDataIndexs[0]).length >= 2
          //       const isSplit = true
          //       if (length === 1 && isSplit) {
          //         this.showMergeButton = false
          //         this.showSplitButton = true
          //       }
          //     }
          //     console.log(this.selectHeadDataIndexs, 'selectHeadDataIndexsd')
          //   }
          // },
        },
      }
    },
    //遍历寻找节点
    findDom(target, domTag) {
      if (target?.tagName === domTag) {
        return target
      } else if (target?.parentNode) {
        return this.findDom(target?.parentNode, domTag)
      } else {
        return null
      }
    },
    //寻找所有选中的dataIndex
    findAllSelectDataIndex(columns, start, end, endColumnsRowIndex) {
      //判断鼠标移动的区域是否跟开始点击的区域是同一行columns
      const isSameRow = this.startColumnsRowIndex === endColumnsRowIndex
      if (isSameRow) {
        return this.findDataIndexsByStartEnd(columns, start, end)
      } else {
        return [start]
      }
    },
    //根据开始结束，寻找可以选中的dataIndex
    findDataIndexsByStartEnd(columns, start, end) {
      const selectDataIndexs = [start]
      const startParentDataIndex = columns.find((column) => column.dataIndex === start).parentDataIndex
      const startIndex = columns.findIndex((column) => column.dataIndex === start)
      const endIndex = columns.findIndex((column) => column.dataIndex === end)
      columns.forEach((item, index) => {
        if (index > startIndex && index <= endIndex) {
          if (startParentDataIndex === item.parentDataIndex) {
            selectDataIndexs.push(item.dataIndex)
          }
        }
      })
      return selectDataIndexs
    },
    //寻找到所有相邻的兄弟columns
    findNearColumns(dataIndex, columns) {
      const parentDataIndex = columns.find((column) => column.dataIndex === dataIndex).parentDataIndex
      const nearColumns = this.tableInstance.getOptionsWithParent(parentDataIndex)
      this.mergeDataSource = nearColumns.map((item, index) => {
        const { newTitle } = this.mergeData.find((item) => item.firstIndex === index) ?? {}
        return { ...item, newTitle }
      })
      console.log('nearColumns', nearColumns)
    },
    //勾选合并的
    onSelectChange(record, selected, selectedRows, nativeEvent) {
      console.log(record, selected, selectedRows, nativeEvent, 'selectedRowKeys')
      //连续选择
      const selectkeys = selectedRows.map((item) => item.key)
      if (selected) {
        this.selfSelectedRowKeys = [...(this.selfSelectedRowKeys ?? []), record.dataIndex]
      } else {
        this.selfSelectedRowKeys = this.selfSelectedRowKeys.filter((item) => item !== record.dataIndex)
      }
      if (this.selfSelectedRowKeys.length >= 2) {
        const startIndex = this.mergeDataSource.findIndex((item) => item.dataIndex === this.selfSelectedRowKeys[0])
        const endIndex = this.mergeDataSource.findIndex((item) => item.dataIndex === this.selfSelectedRowKeys[this.selfSelectedRowKeys.length - 1])
        console.log('startIndex', startIndex)
        console.log('endIndex', endIndex)
        const selectedRowsAll = []
        this.mergeDataSource.forEach((item, index) => {
          if (index >= startIndex && index <= endIndex) {
            selectedRowsAll.push(item)
          }
        })
        this.selectedRows = selectedRowsAll
        this.disabledSelect = this.selectedRowKeys = Array.from(new Set([...selectkeys, ...selectedRowsAll.map((item) => item.key)]))
      } else {
        this.selectedRowKeys = selectkeys
        this.disabledSelect = this.selectedRows = selectedRows
      }
    },
    getCheckboxProps(record) {
      console.log('record', this.disabledSelect)
      //todo禁用已经合并的
      return {
        props: {
          ...record,
          disabled: this.disabledSelect.some((item) => record.key === item),
        },
      }
    },
    //点击合并
    // handleMergeConfirm() {
    //   if (this.selectedRowKeys.length >= 2) {
    //     // this.visibleModal = true
    //     this.selectHeadDataIndexs = this.selectedRowKeys
    //     let max = -1
    //     let min = 999
    //     this.mergeDataSource.forEach((item, index) => {
    //       if (this.selfSelectedRowKeys.includes(item.key)) {
    //         max = Math.max(max, index)
    //         min = Math.min(min, index)
    //       }
    //     })

    //     const dataIndices = []
    //     this.mergeDataSource.forEach((item, index) => {
    //       if (index >= min && index <= max) {
    //         dataIndices.push(item.dataIndex)
    //       }
    //     })
    //     this.mergeData = [...this.mergeData, { dataIndices: dataIndices, firstIndex: min, lastIndex: max, newTitle: this.mergeTitle }]
    //     this.tableInstance.mergeColumns({ title: this.mergeTitle, dataIndices })
    //     console.log('this.selectHeadDataIndexs', this.selectHeadDataIndexs, dataIndices)
    //     // this.mergeTitle = this.selectedRows[0].title
    //     this.visibleMerge = false
    //   } else {
    //     this.$message.warning('请勾选至少2个标题进行合并！')
    //   }
    // },
    //合并关闭
    handleMergeClose() {
      this.visibleMerge = false
      this.selectedRowKeys = []
      this.selectedRows = []
      this.selfSelectedRowKeys = []
      this.disabledSelect = []
    },
    //点击单元格
    clickCell(record, index, column) {
      console.log('点击单元格', column)
    },
    //清除表头选中框及选中数组
    clearSelectTable() {
      this.mergeTitle = ''
      this.selectedHead = false
      this.selectHeadDataIndexs = []
      this.selectBorder = {
        top: 0,
        left: 0,
        width: 0,
        height: 0,
      }
    },
  },
}
</script>
<style scoped lang="less">
#table {
  position: relative;
}

.table {
  /deep/ .ant-table-tbody > tr > td {
    padding: 0;
  }
  /deep/ .ant-table-thead {
    user-select: none;
  }

  /deep/ .ant-table-footer {
    padding: 0;
    position: static;
  }
}
.mergeiconClass {
  display: flex;
  align-items: center;
  justify-content: center;
}
/deep/ .ant-table-filter-dropdown {
  opacity: 0;
}
.menu {
  width: 50px;
  height: 100%;
  line-height: 50px;
  text-align: center;
}
.menu:hover {
  background: #e6f7ff;
}
</style>
